#Copyright 2009-2010 by Ward, David J ( pymethius@ominian.net )
import logging
log = logging.getLogger(__name__)
import sys

from twisted.internet.defer import Deferred

class ResponseHandler(object):
    
    def __init__(self):        
        self.callbacks = {}
        
    def register(self, id):
        d = self.callbacks[id] = Deferred()
                
        return d
    
    def __call__(self, message, environ):
        if not hasattr(self, "callbacks"):
            self.callbacks = {}
            return
        deferred = None
        try:
            deferred = self.callbacks.pop(message.id)
        except KeyError:
            pass
        else:
            if isinstance(deferred, Deferred):
                try:
                    if message.result != False:
                        deferred.callback( (message.result, message,environ,))
                    else:
                        deferred.errback( (message.result, message,environ,))
                except Exception:
                    log.exception("Failure with Response callback")
        
        del(deferred)        
        